import axios from 'axios'
import Vue from 'vue'

// 全局变量记录重发数
axios.defaults.retry = 2;
axios.defaults.retryDelay = 20000;

const $portal = axios.create({
  // baseURL: process.env.API,
  timeout: 60000,
  responseType: 'json',
  headers: {}
});

export default async ({ app, store, router }) => {
  // 是否表单提交
  let isFormSubmit = false, publicAction = true
  // HTTP request拦截
  $portal.interceptors.request.use(config => {
    debugger
    isFormSubmit = false
    publicAction = true
    if (config.headers['Content-Type'] !== 'multipart/form-data') {
      if (config.method === 'post') {
        config.data = {
          ...config.data,
          _t: Date.parse(new Date()) / 1000
        }
      } else if (config.method === 'get') {
        config.params = {
          _t: Date.parse(new Date()) / 1000,
          ...config.params
        }
      }
    }
    // 验证申请状态，是否表单提交，表单提交统一需要弹出提示框
    if (config.headers['sub-form']) {
      isFormSubmit = true
    }
    // 验证是否需要私有处理异常
    if (config.headers['sub-pub']) {
      publicAction = false
    }
    return config
  }, error => {
    return Promise.reject(error)
  });

  // HTTPresponse拦截
  $portal.interceptors.response.use(resp => {
    let data = {};
    if (String(resp.config.url).indexOf('.txt') > -1) {
      data = resp.data
    } else {
      data = resp.data || resp.data[0]
      // if(res)
      if (data.status === 200) {
        if (resp.headers.hasOwnProperty('token')) {
          store.commit('SET_ACCESS_TOKEN', resp.headers.token)
        }
        if (isFormSubmit) {
          // 表单提交成功
          if (data.hasOwnProperty('message')) {
            alert(data.message)
          } else {
            alert("成功")
          }
        }
      } else {
        switch (String(data.status)) {
          case '500':
            if (publicAction) {
              alert(data.message)
            }
            break;
          case '507':
            let dialogMessage = data.message
            if (dialogMessage) {
              alert(dialogMessage)
            }
            break;
        }
      }
    }
    return data
  }, error => {
    let message, stop = false;
    message = app.i18n.t('wrongUrl');
    if (error.response) {
      // url = error.config.url;
      try {
        this.$log('log', 'temp', 'error', { mark: '接口报错', code: String(error.response.status), error: JSON.stringify(error) })
      } catch (e) {}

    } else {
      if (String(error.message).indexOf('timeout') > -1) {
        stop = true
      }
      // else if (String(error.message) === 'Network Error') {
      //   message = app.i18n.t('NetworkWarning');
      // }
    }

   return Promise.reject(error)

  })

  // 后台支持不快，所以打开
  Vue.prototype.$portal = $portal;
  Vue.prototype.$axios = axios
}

export { $portal }
